package com.iotechn.unimall.admin.api.salesSendOrderGoods;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.iotechn.unimall.core.exception.AdminServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.domain.CategoryDO;
import com.iotechn.unimall.data.domain.SalesSendOrderGoodsDO;
import com.iotechn.unimall.data.dto.excel.SkuTotalPriceDTO;
import com.iotechn.unimall.data.dto.warehouse.SalesSendOrderGoodsDTO;
import com.iotechn.unimall.data.mapper.CategoryMapper;
import com.iotechn.unimall.data.mapper.PurchaseWarehouseOrderGoodsMapper;
import com.iotechn.unimall.data.mapper.SalesSendOrderGoodsMapper;
import com.iotechn.unimall.data.model.Page;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class SalesSendOrderGoodsServiceImpl implements SalesSendOrderGoodsService {
    @Autowired
    private SalesSendOrderGoodsMapper salesSendOrderGoodsMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private PurchaseWarehouseOrderGoodsMapper purchaseWarehouseOrderGoodsMapper;

    @Override
    public Page<SalesSendOrderGoodsDO> list(Integer page, Integer limit, Long adminId) throws ServiceException {
        Wrapper<SalesSendOrderGoodsDO> wrapper = new EntityWrapper<SalesSendOrderGoodsDO>();
        /**if (!StringUtils.isEmpty(name)) {
         wrapper.like("username", name);
         }**/
        wrapper.orderBy("id", false);
        Integer count = salesSendOrderGoodsMapper.selectCount(wrapper);
        List<SalesSendOrderGoodsDO> SalesSendOrderGoodsDOS = salesSendOrderGoodsMapper.selectPage(new RowBounds((page - 1) * limit, limit), wrapper);
        return new Page<>(SalesSendOrderGoodsDOS, page, limit, count);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SalesSendOrderGoodsDO create(SalesSendOrderGoodsDO salesSendOrderGoodsDO, Long adminId) throws ServiceException {
        salesSendOrderGoodsDO.setAdminId(adminId);
        Date now = new Date();
        salesSendOrderGoodsDO.setGmtCreate(now);
        salesSendOrderGoodsDO.setGmtUpdate(now);
        salesSendOrderGoodsDO.setSendGoodsAmount(0.0F);
        if(salesSendOrderGoodsDO.getSendGoodsAmount() != null){
            salesSendOrderGoodsDO.setSendGoodsAmount(salesSendOrderGoodsDO.getSendGoodsAmount() * 100F);
        }
        if (salesSendOrderGoodsMapper.insert(salesSendOrderGoodsDO) > 0) {
            salesSendOrderGoodsDO.setId(salesSendOrderGoodsDO.getId());
            return salesSendOrderGoodsDO;
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String update(SalesSendOrderGoodsDO salesSendOrderGoodsDO, Long adminId) throws ServiceException {
        Long id = salesSendOrderGoodsDO.getId();
        if (id == null) {
            return "fail";
        }
        Date now = new Date();
        salesSendOrderGoodsDO.setGmtUpdate(now);
        salesSendOrderGoodsDO.setSendGoodsAmount(0.0F);
        if(salesSendOrderGoodsDO.getSendGoodsAmount() != null){
            salesSendOrderGoodsDO.setSendGoodsAmount(salesSendOrderGoodsDO.getSendGoodsAmount() * 100F);
        }
        if (salesSendOrderGoodsMapper.updateById(salesSendOrderGoodsDO) > 0) {
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String delete(Long id, Long adminId) throws ServiceException {
        if (salesSendOrderGoodsMapper.deleteById(id) > 0) {
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);

    }

    @Override
    public SalesSendOrderGoodsDO detail(Long id, Long adminId) throws ServiceException {
        return salesSendOrderGoodsMapper.selectById(id);
    }

    @Override
    public Page querySkusByWarehouseId(Integer page, Integer limit, Long warehouseId, String skuIds, String search) {
        LinkedList<Long> childrenIds = new LinkedList<>();
        if (skuIds != null && !"".equals(skuIds)) {
            List<CategoryDO> childrenList = categoryMapper.selectList(new EntityWrapper<CategoryDO>().eq("parent_id", skuIds).eq("store_id",0l));
            // 传入类目拥有的三级类目集合
            // 传入类目没有子类目
            if (CollectionUtils.isEmpty(childrenList)) {
                // 则传入类目为三级类目
                childrenIds.add(Long.valueOf(skuIds));
            } else {
                CategoryDO categoryDO = categoryMapper.selectById(skuIds);
                // 检验传入类目是一级还是二级类目
                if (categoryDO.getParentId() != 0L) {
                    //二级分类
                    childrenList.forEach(item -> {
                        childrenIds.add(item.getId());
                    });
                } else {
                    //一级分类
                    childrenList.forEach(item -> {
                        List<CategoryDO> leafList = categoryMapper.selectList(new EntityWrapper<CategoryDO>().eq("parent_id", item.getId()).eq("store_id",0l));
                        if (!CollectionUtils.isEmpty(leafList)) {
                            leafList.forEach(leafItem -> {
                                childrenIds.add(leafItem.getId());
                            });
                        }
                    });
                }
            }
        }
        Integer start = (page - 1) * limit;
        Integer end = limit;
        List<SalesSendOrderGoodsDTO> salesSendOrderGoodsDTOS = salesSendOrderGoodsMapper.querySkusByWarehouseId(warehouseId, childrenIds, start, end, search);
        List<Long> sortedSkuIds = new ArrayList<>();
        Integer count = salesSendOrderGoodsMapper.countSkusByWarehouseId(warehouseId, childrenIds, search);
        return new Page<>(salesSendOrderGoodsDTOS, page, limit, count);
    }


    @Override
    public List<Map<String, Object>> listWarehouseSkusByPara(Long saleSendOrderId, Long warehouseId) throws ServiceException {
        List<Map<String, Object>> result = salesSendOrderGoodsMapper.selectMaps(new EntityWrapper<SalesSendOrderGoodsDO>()
                .eq(saleSendOrderId != null, "send_order_id", saleSendOrderId)
                .eq(warehouseId != null, "warehouse_id", warehouseId)
                .setSqlSelect("send_goods_stock as sendGoodsStock", "send_goods_price as sendGoodsPrice","send_goods_amount as sendGoodsAllPrice", "goods_name as goodsName",
                        "goods_bar_code as barCode", " ifnull((select sum(uwg.allprice/uwg.goods_history_amount) from unimall_warehouse_goods uwg where uwg.sku_id = unimall_sales_send_order_goods.sku_id and uwg.warehouse_id =" + warehouseId + "),0) AS averPrice",
                        "goods_img as img", "goods_id as goodsId", "sku_name as skuName", "spu_name as spuName", "sku_id as skuId", "goods_id as goodsId",
                        "goods_unit as unit", "(select ifnull(sum(uwg.warehouse_sku_stock),0) from unimall_warehouse_goods uwg where uwg.sku_id = unimall_sales_send_order_goods.sku_id and uwg.warehouse_id = " + warehouseId + ") as warehouseSkuNum"));
        result.stream().map(i -> {
            Float originalSendGoodsPrice = Float.valueOf(String.valueOf(i.get("sendGoodsPrice")));
            i.put("sendGoodsPrice", originalSendGoodsPrice / 100);
            Float originalSendGoodsAllPrice = Float.valueOf(String.valueOf(i.get("sendGoodsAllPrice")));
            i.put("sendGoodsAllPrice", originalSendGoodsAllPrice / 100);
            return i;
        }).collect(Collectors.toList());
        return result;
    }
}